package com.egao.common.manage.company;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.egao.common.core.RedisConstants;
import com.egao.common.core.annotation.OperLog;
import com.egao.common.core.web.BaseController;
import com.egao.common.core.web.JsonResult;
import com.egao.common.module.company.entity.Company;
import com.egao.common.module.company.entity.Position;
import com.egao.common.module.company.service.CompanyService;
import com.egao.common.module.company.service.PositionService;
import com.egao.common.module.push.entity.AbilityFormDTO;
import com.egao.common.module.pushInformation.entity.PushInformationPosition;
import com.egao.common.module.pushInformation.entity.PushInformationPositionResult;
import com.egao.common.module.pushInformation.service.PushInformationPositionResultService;
import com.egao.common.module.pushInformation.service.PushInformationPositionService;
import com.egao.common.module.student.entity.Student;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author lym
 * @date 2024/8/26 9:45
 */
@Api(tags = "单位精准匹配")
@RestController
@RequestMapping("${api}")
public class CompanyPushInformation extends BaseController {

    @Resource
    private CompanyService companyService;
    @Resource
    private PositionService positionService;
    @Resource
    private PushInformationPositionService pushInformationPositionService;
    @Resource
    private PushInformationPositionResultService pushInformationPositionResultService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PreAuthorize("hasAuthority('company')")
    @OperLog(value = "单位精准匹配", desc = "匹配信息")
    @ApiOperation("查询详情")
    @PostMapping("/company/push-information/matching")
    public JsonResult matching(@RequestBody AbilityFormDTO abilityFormDTO) {
        if (abilityFormDTO == null || CollectionUtil.isEmpty(abilityFormDTO.getIds())) {
            return JsonResult.error("请选择职位");
        }

        // 查询单位信息
        Company company = companyService.getByUserId(getLoginUserId());
        if (company == null) {
            return JsonResult.error("没有查询到单位信息");
        }

        // 查询职位信息
        List<Position> positionList = positionService.list(new LambdaQueryWrapper<Position>()
                .in(Position::getId, abilityFormDTO.getIds())
        );
        if (CollectionUtil.isEmpty(positionList)) {
            return JsonResult.error("没有查询到职位信息");
        }

        // 查询学生职位匹配情况
        List<PushInformationPosition> pushInformationPositionList = new ArrayList<>();
        for (Position position : positionList) {
            List<Student> studentList = pushInformationPositionService.selectStudent(position.getMajor());
            if (CollectionUtil.isEmpty(studentList)) {
                continue;
            }

            List<PushInformationPosition> list =
                    pushInformationPositionService.computeStudentPositionMatching(studentList, position, company);
            if (CollectionUtil.isEmpty(list)) {
                continue;
            }

            pushInformationPositionList.addAll(list);
        }
        // 没有匹配到职位 返回空数据
        if (CollectionUtil.isEmpty(pushInformationPositionList)) {
            return JsonResult.ok().setData(new ArrayList<>());
        }

        // 结算匹配结果
        List<PushInformationPositionResult> resultList = pushInformationPositionResultService.computeResult(pushInformationPositionList);
        // 记录结果到缓存 缓存30分钟 单位确认提交时取出信息入库
        long cacheTime = 30L;
        stringRedisTemplate.opsForValue().set(RedisConstants.PUSH_POSITION_COMPANY_ID + company.getId(), JSONUtil.toJsonStr(pushInformationPositionList), cacheTime, TimeUnit.MINUTES);
        stringRedisTemplate.opsForValue().set(RedisConstants.PUSH_RESULT_COMPANY_ID + company.getId(), JSONUtil.toJsonStr(resultList), cacheTime, TimeUnit.MINUTES);

        // 构建结果显示给单位查看内容
        Map<String, List<PushInformationPositionResult>> map = resultList.stream().collect(Collectors.groupingBy(PushInformationPositionResult::getPositionName));

        return JsonResult.ok().setData(map).put("keys", map.keySet());
    }
}
